package tech.waterism.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2006
 * </p>
 * <p>
 * Company:
 * </p>
 *
 * @author not attributable
 * @version 1.0
 */

public class DecimalConvert { // 小数转向有指定小数位的字符串
    public static String[] convertArrary(float[] f, int n) {
        String[] str = new String[f.length];
        for (int i = 0; i < f.length; i++) {
            str[i] = convert(f[i], n);
        }
        return str;
    }

    public static String[] convertArrary(double[] f, int n) {
        String[] str = new String[f.length];
        for (int i = 0; i < f.length; i++) {
            str[i] = convert(f[i], n);
        }
        return str;
    }

    public static String convertToSignificantFigures(double num, int significantFigures) {
        if (num == 0) {
            return "0";
        }

        // 计算基于10的对数，以确定数值的数量级
        final int log10 = (int) Math.floor(Math.log10(Math.abs(num)));
        final double scale = Math.pow(10, log10 - significantFigures + 1);

        // 将数字缩放到指定有效数字位数
        double scaled = Math.round(num / scale) * scale;

        // 格式化输出
        return new BigDecimal(scaled).stripTrailingZeros().toPlainString();
    }

    public static String convert(double f, int n) {// double
        String str;
        String pattern = "";
        if (n == 0) {
            pattern = "0";
        }
        if (n > 0) {
            StringBuilder buf = new StringBuilder();
            buf.append("0.");
            for (int i = 0; i < n; i++) {
                buf.append("0");
            }
            pattern = buf.toString();
        }
        DecimalFormat df = new DecimalFormat(pattern);
        str = df.format(f);
        return str;
    }

    public static String convert(BigDecimal f, int n) {// BigDecimal
        String str;
        String pattern = "";
        if (n == 0) {
            pattern = "0";
        }
        if (n > 0) {
            StringBuilder buf = new StringBuilder();
            buf.append("0.");
            for (int i = 0; i < n; i++) {
                buf.append("0");
            }
            pattern = buf.toString();
        }
        DecimalFormat df = new DecimalFormat(pattern);
        str = df.format(f);
        return str;
    }

    public static String convert(float f, int n) {// float
        String str;
        String pattern = "";
        if (n == 0) {
            pattern = "0";
        }
        if (n > 0) {
            StringBuilder buf = new StringBuilder();
            buf.append("0.");
            for (int i = 0; i < n; i++) {
                buf.append("0");
            }
            pattern = buf.toString();
        }
        DecimalFormat df = new DecimalFormat(pattern);
        str = df.format(f);
        return str;
    }
}
